package com.liuhuan.component;

import com.liuhuan.service.api.CrudGeneration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @version 1.0
 * @Author liuhuan
 * @Date 2024/6/27 10:16
 * @WebSocket控制类
 */
@Component
@ServerEndpoint("/TestWebsocket")
@Slf4j
public class WebSocket {
    @Autowired
    private CrudGeneration crudGeneration;
    static  ConcurrentHashMap<String,Session> SessionMap=new ConcurrentHashMap<>();
    @OnOpen
    public void open(Session session){
        SessionMap.put(session.getId(),session);
        log.info("WebSocket已经建立连接");
    }

    @OnMessage
    public void onMessage(Session session, String text) throws Exception {
        CrudGeneration crudGeneration1 = new CrudGeneration();

        BufferedReader reader = crudGeneration1.Generation(text);

        String regex = "\"content\":\"(.*?)\",\"role\"";
        Pattern pattern = Pattern.compile(regex);

        try {
            String inputLine;
            while ((inputLine = reader.readLine()) != null) {
                Matcher matcher = pattern.matcher(inputLine);
                if (matcher.find()) {
                    String content = matcher.group(1);
                    session.getBasicRemote().sendText(content);

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            reader.close();
        }
    }


    //连接关闭时候操作
    @OnClose
    public  void Onclose(Session session){
        SessionMap.remove(session.getId());
        System.out.println("客户端断开");
    }
    @OnError
    public void onError(Session session, Throwable throwable) {
        // 处理错误
        throwable.printStackTrace();
    }

//    @Scheduled(fixedRate = 2000)
//    public void SendMessage() throws IOException {
//        for (String key : SessionMap.keySet()) {
//            SessionMap.get(key).getBasicRemote().sendText("你好，我是服务端");
//        }
//    }
}

